import React, { useEffect, useCallback } from 'react';
import {
  Button,
  Image,
  Popconfirm,
  message,
  Dropdown,
  Typography,
  Tooltip,
  Avatar,
  Space,
  Tag,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  MoreOutlined,
  ShoppingCartOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ProductService } from '../../services/productService';
import { Product } from '../../types';
import { useTableState } from '../../hooks/useTableState';
import { useApiCall } from '../../hooks/useApiCall';
import { formatPrice, formatDate, getStatusTag, getStockStatus } from '../../utils/common';
import DataTable from '../../components/common/DataTable';
import SearchFilterBar from '../../components/common/SearchFilterBar';
import StatsCards from '../../components/common/StatsCards';

const { Title, Text } = Typography;



const ProductList: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  // 使用通用表格状态管理
  const tableState = useTableState<Product>({
    search: '',
    category: '',
    status: ''
  });

  // 使用通用API调用Hook
  const { execute: executeDelete } = useApiCall();

  // 加载商品数据
  const loadProducts = useCallback(async () => {
    tableState.setLoading(true);
    try {
      const response = await ProductService.getProducts({
        page: tableState.state.current,
        limit: tableState.state.pageSize,
        ...tableState.state.filters
      });
      tableState.setData(response.data || [], response.total || 0);
    } catch (error) {
      message.error('加载商品失败');
    } finally {
      tableState.setLoading(false);
    }
  }, [tableState.state.current, tableState.state.pageSize, tableState.state.filters, tableState.setLoading, tableState.setData]);

  // 刷新商品
  const refreshProducts = () => loadProducts();

  // 更新商品
  const updateProduct = async (id: string, data: any) => {
    try {
      await ProductService.updateProduct(id, data);
      message.success('更新成功');
      loadProducts();
    } catch (error) {
      message.error('更新失败');
    }
  };

  // 删除商品
  const deleteProduct = async (id: string) => {
    try {
      await ProductService.deleteProduct(id);
      message.success('删除成功');
      loadProducts();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量更新状态
  const batchUpdateStatus = async (ids: string[], status: string) => {
    try {
      await ProductService.batchUpdateStatus(ids, status);
      message.success('批量更新成功');
      loadProducts();
    } catch (error) {
      message.error('批量更新失败');
    }
  };

  // 初始化
  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '商品管理', path: '/products' },
      { title: '商品列表' }
    ]));
    loadProducts();
  }, [dispatch]); // 移除 loadProducts 依赖，避免循环

  // 监听状态变化重新加载数据
  useEffect(() => {
    loadProducts();
  }, [loadProducts]); // 只依赖 loadProducts，它的依赖已经正确设置

  // 搜索处理
  const handleSearch = (value: string) => {
    tableState.setFilters({ search: value });
  };

  // 筛选处理
  const handleFilterChange = (key: string, value: string) => {
    tableState.setFilters({ [key]: value });
  };

  // 分页处理
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    tableState.setPagination(pagination.current, pagination.pageSize);
  };

  // 行选择处理
  const rowSelection: TableRowSelection<Product> = {
    selectedRowKeys: tableState.state.selectedRowKeys,
    onChange: (selectedRowKeys) => {
      tableState.setSelectedRowKeys(selectedRowKeys);
    },
  };

  // 删除商品
  const handleDelete = async (id: string) => {
    return executeDelete(
      () => ProductService.deleteProduct(id),
      {
        showSuccessMessage: true,
        successMessage: '商品删除成功',
        onSuccess: () => {
          loadProducts();
          tableState.setSelectedRowKeys(
            tableState.state.selectedRowKeys.filter(key => key !== id)
          );
        }
      }
    );
  };

  // 批量删除
  const handleBatchDelete = async () => {
    const promises = tableState.state.selectedRowKeys.map(id =>
      ProductService.deleteProduct(id as string)
    );

    try {
      await Promise.all(promises);
      message.success('批量删除成功');
      tableState.setSelectedRowKeys([]);
      loadProducts();
    } catch (error) {
      message.error('批量删除失败');
    }
  };

  // 更多操作菜单
  const getMoreActions = (record: Product): MenuProps['items'] => [
    {
      key: 'view',
      icon: <EyeOutlined />,
      label: '查看详情',
      onClick: () => navigate(`/products/${record.id}`),
    },
    {
      key: 'edit',
      icon: <EditOutlined />,
      label: '编辑商品',
      onClick: () => navigate(`/products/${record.id}/edit`),
    },
    {
      key: 'copy',
      icon: <ShoppingCartOutlined />,
      label: '复制商品',
      onClick: () => handleCopyProduct(record.id),
    },
    {
      type: 'divider',
    },
    {
      key: 'delete',
      icon: <DeleteOutlined />,
      label: '删除商品',
      danger: true,
      onClick: () => handleDelete(record.id),
    },
  ];

  // 复制商品
  const handleCopyProduct = async (id: string) => {
    try {
      await ProductService.duplicateProduct(id);
      message.success('商品复制成功');
      loadProducts();
    } catch (error) {
      message.error('商品复制失败');
    }
  };



  // 表格列定义
  const columns: ColumnsType<Product> = [
    {
      title: '商品信息',
      key: 'product',
      width: 300,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center', padding: '8px 0' }}>
          <div
            style={{
              width: 60,
              height: 60,
              borderRadius: 8,
              marginRight: 12,
              border: '1px solid #f0f0f0',
              overflow: 'hidden',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#f5f5f5'
            }}
          >
            {record.images?.[0] ? (
              <Image
                src={record.images[0]}
                alt={record.name}
                width={60}
                height={60}
                style={{
                  objectFit: 'cover',
                }}
                fallback=""
                preview={false}
              />
            ) : (
              <div style={{
                color: '#bfbfbf',
                fontSize: '12px',
                textAlign: 'center',
                lineHeight: '60px'
              }}>
                暂无图片
              </div>
            )}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 500, marginBottom: 4, lineHeight: '20px' }}>
              <Tooltip title={record.name}>
                <Text ellipsis style={{ maxWidth: 200, fontSize: '14px' }}>
                  {record.name}
                </Text>
              </Tooltip>
            </div>
            <div style={{ fontSize: 12, color: '#999', marginBottom: 2 }}>
              ID: {record.id}
            </div>
            <div style={{ fontSize: 12, color: '#666' }}>
              <Tag size="small" color="blue">{record.category}</Tag>
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      sorter: true,
      render: (price, record) => {
        const currentPrice = typeof price === 'number' ? price : parseFloat(price) || 0;
        const originalPrice = typeof record.originalPrice === 'number' ? record.originalPrice : parseFloat(record.originalPrice) || 0;

        return (
          <div>
            <div style={{ fontWeight: 500, color: '#f50' }}>
              {formatPrice(currentPrice)}
            </div>
            {originalPrice && originalPrice > currentPrice && (
              <div style={{ fontSize: 12, color: '#999', textDecoration: 'line-through' }}>
                {formatPrice(originalPrice)}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 120,
      sorter: true,
      render: (stock) => getStockStatus(stock),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      filters: [
        { text: '上架中', value: 'active' },
        { text: '已下架', value: 'inactive' },
        { text: '缺货', value: 'out_of_stock' },
      ],
      render: (status) => getStatusTag(status),
    },
    {
      title: '店铺',
      dataIndex: 'shopId',
      key: 'shopId',
      width: 150,
      render: (shopId, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar size="small" style={{ marginRight: 8 }}>
            {record.shopName?.[0] || 'S'}
          </Avatar>
          <Text ellipsis style={{ maxWidth: 100 }}>
            {record.shopName || '未知店铺'}
          </Text>
        </div>
      ),
    },
    {
      title: '销量',
      dataIndex: 'salesCount',
      key: 'salesCount',
      width: 80,
      sorter: true,
      render: (count) => count || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      sorter: true,
      render: (date) => formatDate(date),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/products/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => navigate(`/products/${record.id}/edit`)}
            />
          </Tooltip>
          <Dropdown
            menu={{ items: getMoreActions(record) }}
            trigger={['click']}
          >
            <Button type="text" size="small" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和统计 */}
      <div style={{ marginBottom: '24px' }}>
        <Title level={3} style={{ margin: 0, marginBottom: '16px' }}>
          商品管理
        </Title>
        <StatsCards
          stats={[
            {
              title: '商品总数',
              value: tableState.state.total,
              prefix: <ShoppingCartOutlined />,
              valueStyle: { color: '#1890ff' },
            },
            {
              title: '上架商品',
              value: tableState.state.data?.filter(p => p.status === 'active').length || 0,
              prefix: <CheckCircleOutlined />,
              valueStyle: { color: '#52c41a' },
            },
            {
              title: '缺货商品',
              value: tableState.state.data?.filter(p => p.stock === 0).length || 0,
              prefix: <WarningOutlined />,
              valueStyle: { color: '#faad14' },
            },
            {
              title: '下架商品',
              value: tableState.state.data?.filter(p => p.status === 'inactive').length || 0,
              prefix: <CloseCircleOutlined />,
              valueStyle: { color: '#ff4d4f' },
            },
          ]}
          span={6}
        />
      </div>

      {/* 搜索筛选栏 */}
      <SearchFilterBar
        searchValue={tableState.state.filters.search}
        searchPlaceholder="搜索商品名称、分类、店铺..."
        onSearch={handleSearch}
        filters={tableState.state.filters}
        filterOptions={[
          {
            key: 'category',
            label: '分类',
            placeholder: '选择分类',
            options: [
              { value: '电子产品', label: '电子产品' },
              { value: '服装', label: '服装' },
              { value: '家居', label: '家居' },
              { value: '食品', label: '食品' },
              { value: '图书', label: '图书' },
            ],
            width: 150,
          },
          {
            key: 'status',
            label: '状态',
            placeholder: '商品状态',
            options: [
              { value: 'active', label: '上架中' },
              { value: 'inactive', label: '已下架' },
              { value: 'out_of_stock', label: '缺货' },
            ],
            width: 120,
          },
        ]}
        onFilterChange={handleFilterChange}
        loading={tableState.state.loading}
        onRefresh={refreshProducts}
        onAdd={() => navigate('/products/create')}
        addButtonText="添加商品"
        selectedCount={tableState.state.selectedRowKeys.length}
        batchActions={
          <Popconfirm
            title="确定要删除选中的商品吗？"
            onConfirm={handleBatchDelete}
            okText="确定"
            cancelText="取消"
          >
            <Button danger icon={<DeleteOutlined />}>
              批量删除 ({tableState.state.selectedRowKeys.length})
            </Button>
          </Popconfirm>
        }
      />

      {/* 商品表格 */}
      <DataTable
        columns={columns}
        dataSource={tableState.state.data}
        loading={tableState.state.loading}
        rowSelection={rowSelection}
        onChange={handleTableChange}
        pagination={{
          current: tableState.state.current,
          pageSize: tableState.state.pageSize,
          total: tableState.state.total,
        }}
        emptyText="暂无商品数据"
        emptyDescription={
          tableState.state.filters.search || tableState.state.filters.category || tableState.state.filters.status
            ? '没有找到匹配的商品'
            : undefined
        }
        showAddButton={true}
        addButtonText="添加商品"
        onAddClick={() => navigate('/products/create')}
        hasFilters={!!(tableState.state.filters.search || tableState.state.filters.category || tableState.state.filters.status)}
      />


    </div>
  );
};

export default ProductList;
